package com.hxd.otc.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.widget.BlocksToast;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/4/24 17:47
 * 描  述 :  ${数据处理工具类}
 */
public class DataUtils {

    public static <T> T checkNull(T t) {
        if (t == null) {
            throw new NullPointerException("data not is null");
        }
        return t;
    }

    /**
     * 判断是不是手机号
     *
     * @param phoneNumber 电话号码
     */
    public static boolean isPhoneNumber(@NonNull String phoneNumber) {
        if (TextUtils.isEmpty(phoneNumber)) {
            BlocksToast.get().showToast(R.string.phone_number_not_null);
            return false;
        }
        return true;
    }

    /**
     * 判断是不是手机号(不提示错误信息)
     *
     * @param phoneNumber 电话号码
     */
    public static boolean isPhoneNumberNotHit(@NonNull String phoneNumber) {
        if (TextUtils.isEmpty(phoneNumber)) {
            return false;
        }
        Pattern pattern = Pattern.compile("[1][3-9]\\d{9}");
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }

    /**
     * 判断是不是UUID
     *
     * @param uuid
     * @return
     */
    public static boolean isUUID(@NonNull String uuid) {
        if (TextUtils.isEmpty(uuid)) {
            BlocksToast.get().showToast(R.string.id_not_null);
            return false;
        } else {
            return true;
        }
    }


    /**
     * 判断是不是相同密码
     *
     * @param password
     * @param againPassword
     * @return
     */
    public static boolean isAgainPassword(@NonNull String password, @NonNull String againPassword) {
        if (TextUtils.isEmpty(againPassword)) {
            BlocksToast.get().showToast(R.string.affirm_password_not_null);
            return false;
        } else if (!password.equals(againPassword)) {
            BlocksToast.get().showToast(R.string.two_input_password_not_sure);
            return false;
        }
        return true;
    }

    public static boolean isInvitationCode(String invitationCode){
        if (TextUtils.isEmpty(invitationCode)){
            BlocksToast.get().showToast(R.string.invitation_code_cannot_be_empty);
            return false;
        }
        return true;
    }

    /**
     * 判断是不是昵称
     *
     * @param nickName 昵称
     */
    public static boolean isNickname(@NonNull String nickName) {
        if (TextUtils.isEmpty(nickName)) {
            BlocksToast.get().showToast(R.string.nickname_not_null);
            return false;
        } else if (TextUtils.getTrimmedLength(nickName) < Constant.MIN_NICKNAME_LENGTH) {
            BlocksToast.get().showToast(R.string.nickname_min_length_is_two);
            return false;
        } else if (TextUtils.getTrimmedLength(nickName) > Constant.MAX_NICKNAME_LENGTH) {
            BlocksToast.get().showToast(R.string.nickname_max_length_is_two);
            return false;
        }
        return true;
    }

    /**
     * 判断是不是姓名
     *
     * @param name 姓名
     */
    public static boolean isName(@NonNull String name) {
        if (TextUtils.isEmpty(name)) {
            BlocksToast.get().showToast(R.string.name_not_null);
            return false;
        } else if (TextUtils.getTrimmedLength(name) < Constant.MIN_NAME_LENGTH) {
            BlocksToast.get().showToast(R.string.nickname_min_length_is_two);
            return false;
        } else if (TextUtils.getTrimmedLength(name) > Constant.MAX_NAME_LENGTH) {
            BlocksToast.get().showToast(R.string.name_max_length_is_two);
            return false;
        }
        return true;
    }


    /**
     * dp转换成px
     */
    public static int dp2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px转换成dp
     */
    public static int px2dp(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取屏幕宽
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取屏幕高
     */
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * sp转换成px
     */
    public static int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * px转换成sp
     */
    public static int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    @SuppressLint("CheckResult")
    public static void readAssets(@NonNull final AssetManager manager, @NonNull final String path, @NonNull final OnReaderBufferResult onReaderBufferResult) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                InputStream inputStream = manager.open(path);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int i = -1;
                while ((i = inputStream.read()) != -1) {
                    bos.write(i);
                }
                emitter.onNext(bos.toString());
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(io.reactivex.schedulers.Schedulers.io())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        onReaderBufferResult.onResult(s);
                    }
                });


    }




    public interface OnReaderBufferResult {
        void onResult(String data);
    }

    public static boolean isEmpty(@NonNull String text) {
        return TextUtils.isEmpty(text) || TextUtils.getTrimmedLength(text) <= 0;
    }


    public static double mul(double number1, double number2) {
        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(number1));
        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(number2));
        return Double.valueOf(bigDecimal1.multiply(bigDecimal2).toString());
    }

    public static double mul(double number1, double number2, int scale) {
        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(number1));
        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(number2));
        return Double.valueOf(bigDecimal1.multiply(bigDecimal2).setScale(scale, RoundingMode.DOWN).toString());
    }

    public static double mulOfBigDecimal(double number1, double number2, int scale) {
        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(number1));
        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(number2));
        return Double.valueOf((bigDecimal1.multiply(bigDecimal2)).setScale(scale, RoundingMode.DOWN).toString());
    }

    public static double mulOfBigDecimal(double number1, double number2) {
        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(number1));
        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(number2));
        return Double.valueOf((bigDecimal1.multiply(bigDecimal2)).toString());
    }

    /**
     * 除法
     */
    public static double divide(double number1, double number2, int scale, RoundingMode roundingMode) {
        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(number1));
        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(number2));
        return Double.valueOf(bigDecimal1.divide(bigDecimal2, scale, roundingMode).toString());
    }

    /**
     * 不能输入为空的价格
     *
     * @param singlePriceStr 单价
     * @param sectionPrice
     * @return
     */
    @SuppressLint("StringFormatMatches")
    public static boolean checkPublishUnitPrice(@NonNull String singlePriceStr, Double... sectionPrice) {

        if (TextUtils.isEmpty(singlePriceStr)) {
            BlocksToast.get().showToast(R.string.ad_single_price_not_is_null);
            return false;
        }

        Double singlePrice = Double.valueOf(singlePriceStr);

        if (singlePrice == 0) {
            BlocksToast.get().showToast(R.string.ad_single_price_not_is_zero);
            return false;
        }

        if (sectionPrice == null || (sectionPrice.length == 2 && singlePrice >= sectionPrice[0] &&
                singlePrice <= sectionPrice[1])) {
            return true;
        } else {
            if (sectionPrice.length == 2) {
                BlocksToast.get().showToast(UIUtils.getContext().getString(R.string.price_whiles_not_min, sectionPrice[0], sectionPrice[1]));
            }
            return false;
        }
    }

    /**
     * 是否是登陆密码
     *
     * @param loginPassword 需要校验的登陆密码
     * @return true:合法登陆密码；false：非法登陆密码
     */
    public static boolean isLoginPassword(String loginPassword) {
        return isLoginPassword(loginPassword, ResourceUtil.getString(R.string.password));
    }

    /**
     * 是否是登陆密码
     *
     * @param loginPassword      需要校验的登陆密码
     * @param loginPasswordAlias 交易密码别名，如‘新登陆密码’，用于提示使用
     * @return true:合法登陆密码；false：非法登陆密码
     */
    public static boolean isLoginPassword(String loginPassword, String loginPasswordAlias) {
        loginPassword = StringUtil.emptyIfNull(loginPassword).trim();
        if (TextUtils.isEmpty(loginPassword)) {
            BlocksToast.get().showToast(R.string.placeholder_data_is_not_empty, loginPasswordAlias);
            return false;
        }
        if (!Pattern.matches(Constant.REGEX_LOGIN_PASSWORD, loginPassword)) {
            BlocksToast.get().showToast(R.string.login_password_rule, loginPasswordAlias, Constant.LOGIN_PASSWORD_MIN_LENGTH, Constant.LOGIN_PASSWORD_MAX_LENGTH);
            return false;
        }
        return true;
    }

    /**
     * 是否是交易密码
     *
     * @param payPassword      需要校验的交易密码
     * @param payPasswordAlias 交易密码别名，如‘新交易密码’，用于提示使用
     * @return true:合法交易密码；false：非法交易密码
     */
    public static boolean isPayPassword(String payPassword, String payPasswordAlias) {
        payPassword = StringUtil.emptyIfNull(payPassword).trim();

        if (TextUtils.isEmpty(payPassword)) {
            BlocksToast.get().showToast(R.string.placeholder_data_is_not_empty, payPasswordAlias);
            return false;
        }

        if (!Pattern.matches(Constant.REGEX_PAY_PASSWORD, payPassword)) {
            BlocksToast.get().showToast(R.string.pay_password_rule, payPasswordAlias, Constant.PAY_PASSWORD_MIN_LENGTH, Constant.PAY_PASSWORD_MAX_LENGTH);
            return false;
        }
        return true;
    }


    /**
     * 是否是交易密码
     *
     * @param payPassword 需要校验的交易密码
     * @return true:合法交易密码；false：非法交易密码
     */
    public static boolean isPayPassword(String payPassword) {
        return isPayPassword(payPassword, ResourceUtil.getString(R.string.pay_password));
    }

    /**
     * 是否是合法邮箱
     * @param email 邮箱地址
     */
    public static boolean isEmail(String email) {
        return isEmail(email,ResourceUtil.getString(R.string.email));
    }

    /**
     * 是否是合法邮箱
     * @param email 邮箱地址
     * @param emailAlias 邮箱别名，如‘新邮箱’，用于提示使用
     */
    public static boolean isEmail(String email,String emailAlias) {
        email = StringUtil.emptyIfNull(email).trim();
        if (TextUtils.isEmpty(email)){
            BlocksToast.get().showToast(R.string.placeholder_data_is_not_empty, emailAlias);
            return false;
        }

        if (!Pattern.matches(Constant.REGEX_EMAIL, email)) {
            BlocksToast.get().showToast(ResourceUtil.getString(R.string.please_enter_the_correct_mailbox,emailAlias));
            return false;
        }
        return true;
    }



    /**
     * 是否是验证码
     *
     * @param verCode
     * @return true:合法验证码；false：非法验证码
     */
    public static boolean isVerCode(String verCode) {
        verCode = StringUtil.emptyIfNull(verCode).trim();
        if (TextUtils.isEmpty(verCode)) {
            BlocksToast.get().showToast(R.string.please_input_ver_code);
            return false;
        }
        return true;
    }
}